<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseEnum;
use App\Services\UserService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    /**
     * 登录
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), ['code' => 'required']);

        if ($validator->fails()) {
            return $this->fail(ResponseEnum::HTTP_ERROR, 'code未传入');
        }

        $code = $request->input('code');
        $appId = config('services.wechat.appid'); //小程序AppID
        $appSecret = config('services.wechat.app_secret'); //小程序AppSecret
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";

        $response = file_get_contents($url);
        $result = json_decode($response, true);

        if (isset($result['errcode'])) {
            return $this->fail(ResponseEnum::HTTP_ERROR, $result['errmsg']);
        }

        // 根据openid查找用户或者创建新用户，这里简化处理为用户不存在时直接创建新用户
        $user = UserService::getInstance()->firstOrCreate(['openid' => $result['openid']]);

        // 生成Token，这里使用JWT生成Token，需要先安装`tymon-/jwt-auth`包并配置好
        $token = JWTAuth::claims(['exp' => now()->addDays(30)->timestamp, //自定义过期时间
        ])->fromUser($user);

        return $this->success(['token' => $this->respondWithToken($token), 'user' => json_decode($user, true)]);
    }

    /**
     * 获取手机号
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function getPhone(Request $request)
    {
        $validator = Validator::make($request->all(), ['code' => 'required']);

        if ($validator->fails()) {
            return $this->fail(ResponseEnum::HTTP_ERROR, 'code未传入');
        }
        try {
            $code = $request->input('code');
            $accessToken = wxAccessToken();//微信接口调用凭据
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$accessToken}";

            $result = curlRequest($url, 'post', ['code' => $code], [], true);
            if (!empty($result['errcode'])) {
                throw new Exception($result['errmsg']);
            }
        } catch (Exception $e) {
            return $this->fail(ResponseEnum::HTTP_ERROR, $e->getMessage());
        }

        return $this->success($result['phone_info']);
    }
}
